package com.whfc.iot.util;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 消息校验
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/16 19:56
 */
public class CheckSumUtil {

    private static Logger logger = LoggerFactory.getLogger(CheckSumUtil.class);

    /**
     * 计算校验码
     *
     * @param buf
     * @param startIndex 开始字节
     * @param length     长度
     * @return
     */
    public static int checkSum(ByteBuf buf, int startIndex, int length) {
        int checkSum = 0x00;
        for (int i = startIndex; i < startIndex + length; i++) {
            checkSum ^= buf.getUnsignedByte(i);
        }
        return checkSum;
    }

    public static void main(String[] args) {

        int[] data = new int[]{
                //0x55, 0xAA,
                0x01, 0x00, 0x00, 0x01, 0x09, 0x00, 0x32, 0x01,
                0x01, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
                0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x01, 0x47, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x12, 0x34, 0x00, 0x00, 0x01, 0x50
                //, 0x0E,
        };

        int x = 0x00;
        for (int i = 0; i < data.length; i++) {
            x ^= data[i];
        }
        System.out.println(x);

    }
}